<?php
namespace Common\Model;
use Think\Model;

/**
 * Class GateRecordModel
 * @package Common\Model
 * 河道闸门运行记录表
 */
class GateRecordModel extends BaseModel{
    public $pix = "";
    public $fieldsStr = '*';
    public $orderStr = 'date desc';

    public function get_list_use_page($map=array(), $cur_page, $rows_num){
        if(isset($map['gateid'])){
            $map['gateid'][0] = 'eq';
            $map['gateid'][1] = str_replace('%', '', $map['gateid'][1]);
            $station_id = str_replace('%', '', $map['gateid'][1]);
            $station_id = explode(',', $station_id);
        }
        if($map['start']&& $map['end']){
            $map['start'][1] = str_replace('%', '', $map['start'][1]);
            $map['end'][1] = str_replace('%', '', $map['end'][1]);
//            $date_str = '(date>=\''.$map['start'][1].' 00:00:00'.'\' and date<=\''.$map['end'][1].' 23:59:59'.'\') ';
            $date_str = '((gate_start >= \''.$map['start'][1].' 00:00:00\' AND gate_start <= \''.$map['end'][1].' 23:59:59\') OR
            (gate_start <= \''.$map['start'][1].' 00:00:00\' AND gate_off >= \''.$map['end'][1].' 23:59:59\') OR
            (gate_off >= \''.$map['start'][1].' 00:00:00\' AND gate_off <= \''.$map['end'][1].' 23:59:59\')
            OR (gate_off is null AND gate_start <=  \''.$map['end'][1].' 23:59:59\'))';
            unset($map['start']);
            unset($map['end']);
        }
        $map = filter_query_map($map);
        $station_model = D('Gate');
        $where_str = '';
        for($i=0;$i<count($station_id);$i++){
            $where_str .= 'gateid='.$station_id[$i];
            if($i < count($station_id)-1){
                $where_str .= ' or ';
            }
        }
        if($date_str&&$where_str)
            $where_str = $date_str.' and ('.$where_str.')';
        else if($date_str&&!$where_str)
            $where_str = $date_str;
        unset($map['gateid']);
        if($where_str){
            $count = M('GateRecord')->where($map)->where($where_str)->count();
            $list = $this->where($map)->where($where_str)->order($this->orderStr)->page($cur_page.",$rows_num")->select();
        }else if(!$where_str&&!empty($map)){
            $count = M('GateRecord')->where($map)->count();
            $list = $this->where($map)->order($this->orderStr)->page($cur_page.",$rows_num")->select();
        }else if(empty($station_id)){
            $count = M('GateRecord')->count();
            $list = $this->order($this->orderStr)->page($cur_page.",$rows_num")->select();
        }else if(!empty($station_id)){
            $count = 0;
            $list = array();
        }
        foreach($list as $k => $v){
            $temp_gate = ($station_model->queryObj($v['gateid'], 'id'));
            $list[$k]['sta_name'] = $temp_gate['gate_name'];
            $list[$k]['weather'] = weather_status_option($list[$k]['weather'], false);
            $list[$k]['status_index'] = $list[$k]['status'];
            if($list[$k]['status']==0){
                $time = strtotime($list[$k]['gate_off'])-strtotime($list[$k]['gate_start']);
                $list[$k]['work_time'] = round(timestamp_to_time('hour', $time), 2);
            }else if($list[$k]['status']==1){
                $time = strtotime(getNowTime())-strtotime($list[$k]['gate_start']);
                $list[$k]['work_time'] = round(timestamp_to_time('hour', $time), 2);
            }
            $list[$k]['status'] = gate_status_option($list[$k]['status'], false);
        }
        //如果泵站没有泵机，则他就没有记录
        return array('total'=>$count, 'list'=>$list);
    }

    public function filter_all($pid){
        $admin_model = D('MobileAdmin');
        $station_model = D('Gate');
        $staion = $station_model->queryObj($pid, 'id');
        $list = $this->queryField('gateid', $pid);
        foreach($list as $k => $v){
            $admin = $admin_model->queryObj($list[$k]['opr'], 'id');
            $list[$k]['opr'] = $admin['realname'];
            $list[$k]['station'] = $staion['gate_name'];
            $list[$k]['gateid'] = $staion['gate_number'];
        }
        return $list;
    }

    /**
     * @param $pid
     * @return int
     * 返回运行记录最新一条
     */
    public function get_last_one($pid){
        $map['gateid'] = array('eq', $pid);
        $one = $this->where($map)->order('date desc')->find();
        return $one?$one['status']:999;
    }

    public function get_last_one_record($pid){
        $map['gateid'] = array('eq', $pid);
        $one = $this->where($map)->order('date desc')->find();
        return $one?$one:false;
    }

    /**
     * @param $pid
     * @param $data
     * 关闭设备设定时间，包括关闭、故障
     */
    public function set_device_off($pid, $data){
        $last_one = $this->get_last_one_record($pid);
        if($data['status'] == 0){
            //如果上一条是开机，更新上一条
            if($last_one['status'] == 1){
                $last_one['status'] = $data['status'];
                $last_one['gate_off'] = getNowTime();
                $last_one['opr'] = $data['opr'];
                return $this->save($last_one);
            }
        }else if($data['status'] == -2){
            //如果上一条是开机，更新上一条
            if($last_one['status'] == 1){
                $last_one['status'] = $data['status'];
                $last_one['gate_off'] = getNowTime();
                $last_one['opr'] = $data['opr'];
                return $this->save($last_one);
            }else{
                return $this->addObj($data);
            }
        }
        return false;
    }

    public function addObj_mobile($post, $f_title='id'){
        $last_one = $this->get_last_one_record($post['gateid']);
        if($last_one['status'] == 1){
            //如果前面一条是开机，那说明可能数据传输出错了，先把上一条关机，然后再重新保存一条开机记录
            $this->delete($last_one['id']);
        }
        //判重
        $data[$f_title] = array("eq", $post[$f_title]);
        $one = $this->where($data)->find();
        $post['date'] = getNowTime();
        switch($post['status']){
            case 1:
                $post['gate_start'] = getNowTime();
                break;
            case 0:
                $post['gate_off'] = getNowTime();
                break;
            default:
                $post['gate_off'] = getNowTime();
                break;
        }
        if(!$one){
            //如果没有记录，就添加
            return $this->add($post);
        }else{
            //反之更新
            return $this->save($post);
        }
    }

    public function clear_error_record($last_date=''){
        $config = array(
            'station_model' => 'Gate',
            'fy_model' => 'Gate',
            'fy_frg_key' => 'id',
            'record_frg_key' =>'gateid',
        );
        /**
         * 1.先清除设备已经被删除了的
         * 2.清除关着机，以前有开机项的
         * 3.清除开着机，以前有开机项的
         */
        //关着机、开着机
        $station_model = D($config['station_model']);
        $fy_model = D($config['fy_model']);
        $fys = $fy_model->select();
        foreach($fys as $fy){
            //查找设备所属设施是否已经被删除
            $station = $station_model->queryObj($fy[$config['fy_frg_key']], 'id');
            $last_record = $this->get_last_one_record($fy['id']);
            $fy_status = $last_record['status'];
            $del_map = array();
            $del_map[$config['record_frg_key']] = array('eq', $fy['id']);
            //开着机
            if($fy_status == 1){
                $del_map['id'] = array('lt', $last_record['id']);
                $this->where($del_map)->delete();
            }
            //关着机
            if($fy_status == 0 || $fy_status == -2){
                $del_map['status'] = array('eq', 1);
                $this->where($del_map)->delete();
            }
            //如果设施不存在，则删除这个设备
            if(!$station){
                $fy_model->delete($fy['id']);
            }
        }
        //如果设备不存在
        if($last_date){
            $date_map['date'] = array('egt', $last_date);
            $records = $this->where($date_map)->order($this->orderStr)->select();
        }else{
            $records = $this->order($this->orderStr)->select();
        }
        $temp_record_ids = array();
        foreach($records as $record){
            $fy = $fy_model->queryObj($record[$config['record_frg_key']], 'id');
            if(!$fy){
                $temp_record_ids[] = $record['id'];
            }
        }
        $this->delete(implode(',', array_filter($temp_record_ids)));
    }

    public function bz_record($fy, $list, $start_date, $end_date){
        foreach($list as $k => $item){
            if(!valdate_time($item['gate_start'])){
                unset($list[$k]);
                continue;
            }
            if(!valdate_time($item['gate_off'])){
                $item['gate_off'] = date('Y-m-d H:i:s');
            }
            if($item['gate_start'] < $start_date)
                $start = $start_date;
            else
                $start = $item['gate_start'];
            if($item['gate_off'] > $end_date)
                $end = $end_date;
            else
                $end = $item['gate_off'];
            if($start > date('Y-m-d H:i:s')){
                $start = date('Y-m-d H:i:s');
            }
            if($end > date('Y-m-d H:i:s')){
                $end = date('Y-m-d H:i:s');
            }
            $time = strtotime($end) - strtotime($start);
            $list[$k]['date'] = substr($list[$k]['date'],0,10);
            $list[$k]['start'] = $start;
            $list[$k]['end'] = $end;
            $list[$k]['time'] = round(timestamp_to_time('hour', $time), 1);
            $list[$k]['weather'] = weather_status_option($list[$k]['weather'], false);
            $tmx = D('MobileAdmin')->queryObj($list[$k]['opr'], 'id');
            $list[$k]['opr'] = $tmx['realname'];
        }
        return $list;
    }
}